

package blogs.eidos.cloud.framework.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import net.bigdata.cloud.framework.common.api.HttpCodeEnum;
import net.bigdata.cloud.framework.constant.CommonRedisKey;
import net.bigdata.cloud.framework.shiro.util.JwtTokenUtil;
import net.bigdata.cloud.framework.shiro.util.JwtUtil;
import net.bigdata.cloud.framework.shiro.vo.LoginUser;
import net.dgg.framework.tac.redis.bean.DggRedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.stereotype.Component;


/**
 * 获取登录信息工具类
 *
 * @author Eidos
 * @date 2018-11-08
 */
@Slf4j
@Component
public class LoginUtil {

    private static DggRedisUtils<String> dggRedisUtils;

    public LoginUtil(DggRedisUtils<String> dggRedisUtils) {
        LoginUtil.dggRedisUtils = dggRedisUtils;
    }

    /**
     * 获取当前登录用户对象
     *
     * @return
     */
    public static LoginUser getLoginUser() {
        try {
            // 获取当前登录用户
            String token = JwtTokenUtil.getToken();
            String username = JwtUtil.getUsername(token);
            if (StringUtils.isBlank(username)) {
                throw new AuthenticationException(HttpCodeEnum.ACCESS_DENIED_ERROR.getMessage());
            }
            return JSONObject.parseObject(dggRedisUtils.get(String.format(CommonRedisKey.LOGIN_USER, username)), LoginUser.class);
        }catch (Exception e){
            throw new AuthenticationException(HttpCodeEnum.ACCESS_DENIED_ERROR.getMessage());
        }

    }

    /**
     * 获取当前登录用户的ID
     *
     * @return
     */
    public static Long getUserId() {
        LoginUser user = getLoginUser();
        if (user == null) {
            return null;
        }
        return user.getId();
    }

    /**
     * 获取当前登录用户的账号
     *
     * @return
     */
    public static String getUsername() {
        LoginUser user = getLoginUser();
        if (user == null) {
            return null;
        }
        return user.getUserName();
    }

}
